﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Windows.Forms;
using EqRepair.Code.Classes;
using EqRepair.Code.Data;
using EqRepair.Code.Enums;
using Label=System.Web.UI.WebControls.Label;

namespace EqRepair.Web
{
	public partial class ManualReq : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
            
		}

		protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
		{

		}

		protected void ButtonNew_Click(object sender, EventArgs e)
		{
			LabelEq0.Visible = false;
			Panel1.Visible = false;
			TreeViewAgrer.Nodes.Clear();
			using (var db = new DataClasses2DataContext())
			{
				int CurOr;
				if (Int32.TryParse(DropDownList1.SelectedValue, out CurOr))
				{
					var JoinQuery =
						from lnk in db.EquipmentInOrganizations
						join mgr in db.Equipments on lnk.Equipment equals mgr
						//join msg in Program.database.Messages on mgr equals msg.MsgGroup
						where lnk.OrganizationId == CurOr && lnk.ParentID == 0
						select new {lnk.Id, mgr.Name, lnk.InstallDate, lnk.LastRepairDate, mgr.LifeTime};

					GridViewCurEq.DataSource = JoinQuery;
					GridViewCurEq.DataBind();
					GridViewCurEq.Visible = true;
					LabelEq.Visible = true;
				}

			}
		}

		protected void ButtonCreateReq_Click(object sender, EventArgs e)
		{
			try
			{
				if (TreeViewAgrer.SelectedNode != null)
				{
					int OEId = Int32.Parse(TreeViewAgrer.SelectedValue);
					using (var db = new DataClasses2DataContext())
					{
						var Req = db.RequestForRepairs.Where(x => x.EquipmentInOrganization.Id == OEId && (x.Status == 1 || x.Status == 2));
						if (Req.Count() == 0)
						{
							var rr = new RequestForRepair
							         	{
							         		CreatedById = new SessionAuthentification(Session).GetCurrentUserID(),
							         		Status = ((short) StatusRequest.New),
							         		CreatedDateTime = DateTime.Now,
							         		//OrganizationEquipmentId = Int32.Parse(GridViewCurEq.SelectedRow.Cells[1].Text)
							         		OrganizationEquipmentId = OEId,
							         		Descr = TextBoxDes.Text

							         	};
							db.RequestForRepairs.InsertOnSubmit(rr);
							db.SubmitChanges();
							Panel1.Controls.Add(new Label
							                    	{
							                    		Text =
							                    			"Заявка успешно создана: замена " + TreeViewAgrer.SelectedNode.Text + " (код " +
							                    			TreeViewAgrer.SelectedValue + ")" +
							                    			" в организации " + DropDownList1.SelectedItem.Text
							                    	});
						}
						else
						{
							string Nums = "";
							//foreach (var x in db.RequestForRepairs)
							foreach (var x in Req)
							{
								//Select(x => x.EquipmentInOrganization.Id == OEId && (x.Status == 1 || x.Status == 2)
								//if (x.EquipmentInOrganization.Id == OEId && (x.Status == 1 || x.Status == 2))
								{
									if (Nums == "")
									{
										Nums = x.Id.ToString();
									}
									else Nums += ", " + x.Id;
								}
							}
							Panel1.Controls.Add(new Label
							                    	{
							                    		Text =
							                    			"На данное оборудование уже есть незакрытые заявки: №" + Nums
							                    	});
						}
					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show("Произошла непредвиденная ошибка. " + ex.Message, "Внимание.", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
			}

		}

		protected void GridViewCurEq_SelectedIndexChanged(object sender, EventArgs e)
		{
			//
			//TreeNode tr=new TreeNode();
			LabelEq0.Visible = true;
			Panel1.Visible = false;
			TreeViewAgrer.Nodes.Clear();
			TreeViewAgrer.Nodes.Add(AccessData.GetTreeAgregInOrg(Int32.Parse(GridViewCurEq.SelectedRow.Cells[1].Text)));
			TreeViewAgrer.ExpandAll();

		}

		protected void TreeViewAgrer_SelectedNodeChanged(object sender, EventArgs e)
		{
		    TextBoxDes.Text = "";

            Panel1.Visible = true;
		}
	}
}